package cn.wolfcode.shop.cloud.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    public static void addCookie(String cookieName,
                                 String cookieValue,
                                 int expireTime,
                                 HttpServletResponse response) {

        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setDomain("localhost");//作用域
        cookie.setPath("/");          //生效路径
        cookie.setMaxAge(expireTime); //过期时间
        response.addCookie(cookie); //使用response对象响应回去
    }


    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        //获取请求中的所有cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //如果cookie的名字和我们制定的一样,返回cookie的value
                if (cookie.getName().equals(cookieName)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
